
const Q = require('q');
const path =require('path')
const shell = require('shelljs');
const fs = require('fs')
const config = require('./config')
// const copyPage = require('./copy')
function copyPage (from, to){
  shell.cp('-Rf', from, to)
}
function init(git_ssh_url, projectName, targetBranch) {
  deferred = Q.defer();
  if (!git_ssh_url || !projectName) {
      return deferred.reject('项目地址或者项目名称为空');
  }
  repository = git_ssh_url;
  repositoryName = projectName;
  clonePath = path.join(__dirname, '../projects/' + projectName);
  const projects_path = path.join(__dirname, '../projects/');
  shell.exec('exit 0');
  if (shell.test('-e', clonePath)) {
      shell.cd(clonePath);
      let currentBranch = shell.exec('git symbolic-ref --short -q HEAD', {async: false, silent: true}).stdout;
      if(currentBranch != targetBranch) {
          let outInfo = shell.exec('git branch', {async: false, silent: true}).stdout;
          let gitcmd = outInfo.indexOf(targetBranch) >= 0 ? ('git checkout ' + targetBranch) : ('git checkout -b ' + targetBranch + ' origin/' + targetBranch);
          shell.exec('git pull && ' + gitcmd, {async: false, silent: true});
      }
      shell.exec('git pull', {async: false, silent: true}, function (code, stdout, stderr) {
          if (code != 0) {
              console.log(stderr);
              return deferred.reject('git pull error');
          }
          console.log(stdout);
          console.log('git pull run success');
          return buildTest(projectName, targetBranch);
      })
  } else {
      if (!fs.existsSync(projects_path)) {
          fs.mkdirSync(projects_path);
      }
      shell.cd(projects_path);
      shell.exec('git clone ' + repository, function (code, stdout, stderr) {
          if (code != 0) {
              console.log(stderr);
              return deferred.reject('git clone error');
          }
          console.log('git clone success');
          shell.cd(clonePath);
          let outInfo = shell.exec('git branch', {async: false, silent: true}).stdout;
          let gitcmd = outInfo.indexOf(targetBranch) >= 0 ? ('git checkout ' + targetBranch) : ('git checkout -b ' + targetBranch + ' origin/' + targetBranch);
          shell.exec(gitcmd, {async: false, silent: true});
          return buildTest(projectName, targetBranch);
      })
  }
  return deferred.promise;
}

// 构建项目
function buildTest(projectName, targetBranch) {
  shell.cd(clonePath);
  shell.exec('npm config set registry https://registry.npm.taobao.org && npm install', {async: true, silent: true}, function (code, stdout, stderr) {
      if (code != 0) {
          console.log(stderr);
          return deferred.reject('npm install error');
      }
      console.log('npm install success');
      // shell.rm('-rf', path.join(clonePath, 'dist'));
      // let testCommand = config[repositoryName].commands.test || 'npm run test'; //构建测试文件命令行
      // shell.exec(testCommand, {async: true, silent: true}, function (code, stdout, stderr) {
      //     if (code != 0) {
      //         console.log(stderr);
      //         return deferred.reject('npm run test fail');
      //     }
      //     console.log('npm run test success');
      //     copyPage(repositoryName, 'test'); // copy到测试目录
      //     if(targetBranch != '1.0.0') {
      //         shell.exec('exit 0');
      //         deferred.resolve('build success and finish');
      //         return; // 提测时只构建测试文件
      //     }
      //     // 构建最终上线文件
      //     shell.rm('-rf', path.join(clonePath, 'dist'));
      //     let buildCommand = config[repositoryName].commands.build || 'npm run build'; //构建预上线文件命令行
      //     shell.exec(buildCommand, {async: true, silent: true}, function (code, stdout, stderr) {
      //         if (code != 0) {
      //             console.log(stderr);
      //             return deferred.reject('npm run build fail');
      //         }
      //         console.log('npm run build success');
      //         copyPage(repositoryName, 'online'); //copy到上线正式目录
              
      //         // 每次合并master构建后，都切换到测试分支，便于平台读取config.json信息（测试分支是最新的）
      //         shell.exec('git checkout ' + config[projectName].testEnv.targetBranch, {async: false, silent: false}); 
      //         shell.exec('exit 0');
      //         deferred.resolve('build success and finish');
      //     })
      // })
      // 构建最终上线文件
      shell.rm('-rf', path.join(clonePath, 'dist'));
      let buildCommand = config[repositoryName].commands.build || 'npm run build'; //构建预上线文件命令行
      shell.exec(buildCommand, {async: true, silent: true}, function (code, stdout, stderr) {
          if (code != 0) {
              console.log(stderr);
              return deferred.reject('npm run build fail');
          }
          console.log('npm run build success');
          copyPage('dist', path.resolve(__dirname,'../static/'+projectName)); //copy到上线正式目录
          
          // 每次合并master构建后，都切换到测试分支，便于平台读取config.json信息（测试分支是最新的）
          // shell.exec('git checkout ' + config[projectName].testEnv.targetBranch, {async: false, silent: false}); 
          shell.exec('exit 0');
          deferred.resolve('build success and finish');
      })
  })
}
module.exports = {
  init,
  buildTest
}